class Car{
	constructor(){
		this.tbody = document.querySelector("tbody");
		this.tfoot = document.querySelector("tfoot");
		this.deleteAll = document.querySelector(".deleteAll");
		this.getData();
	}
	getData(){
		if(localStorage.getItem("goodsMsg")){
			this.gm = JSON.parse(localStorage.getItem("goodsMsg"));
		}else{
			this.gm = [];
		}
		this.init();
	}
	init(){
		var str = "";
		for(var i=0;i<this.gm.length;i++){
			str += `<tr index = "${this.gm[i].goodsId}">
					<td><input type="checkbox" checked/></td>
					<td><img src="${this.gm[i].msg.img}"/></td>
					<td>${this.gm[i].msg.name}</td>
					<td>${this.gm[i].msg.price}</td>
					<td><input type="number" min="1" value="${this.gm[i].num}"></td>
					<td>${this.gm[i].num * this.gm[i].msg.price}</td>
					<td class="delete">删除</td>
				</tr>`;
		}
		this.tbody.innerHTML = str;
		this.judge();
		this.addEvent();
	}
	addEvent(){
		var that = this;
		this.tbody.onclick = function(eve){
			var e = eve || window.event;
			var tar = e.target || e.srcElement;
			if(tar.className == "delete"){
				that.id = tar.parentNode.getAttribute("index");
				tar.parentNode.remove();
				that.changeData(function(i){
					that.gm.splice(i,1);
				});
			}
			that.judge();
		}
		this.deleteAll.onclick = function(){
			that.gm = [];
			localStorage.setItem("goodsMsg",JSON.stringify(that.gm));
			that.tbody.innerHTML = null;
			this.parentNode.remove();
		}
		this.tbody.oninput = function(eve){
			var e = eve || window.event;
			var tar = e.target || e.srcElement;
			if(tar.type == "number"){
				that.id = tar.parentNode.parentNode.getAttribute("index");
				that.changeData(function(i){
					that.gm[i].num = tar.value;
				});
				tar.parentNode.nextElementSibling.innerHTML = tar.parentNode.previousElementSibling.innerHTML * tar.value;
			}
		}
	}
	judge(){
		this.sumNum = 0;
		this.sumPrice = 0;
		for(var i=0;i<this.tbody.children.length;i++){
			var attribute = this.tbody.children[i].firstElementChild.firstElementChild;
			if(attribute.checked == true){
				this.sumNum += parseInt(this.tbody.children[i].children[4].firstElementChild.value);
				this.sumPrice += parseInt(this.tbody.children[i].children[5].innerHTML);
			}
			this.tfoot.firstElementChild.children[1].innerHTML = this.sumNum;
			this.tfoot.firstElementChild.children[2].innerHTML = this.sumPrice;
		}
	}
	changeData(cb){
		for(var i=0;i<this.gm.length;i++){
			if(this.gm[i].goodsId == this.id){
				cb(i);
				break;
			}
		}
		localStorage.setItem("goodsMsg",JSON.stringify(this.gm));
	}
}
new Car;
